import { useEffect, useState, useMemo, useCallback, useRef } from "react";
import { useDeviceListStore } from '@/hooks';
import { IProduct } from '@/config/product';
import { isSameDevice } from '@/utils'
import languageModal from "@/models/language";
import homesModel from "@/models/homes";
import deviceListModal, { deviceDefaultName } from "@/models/deviceList";
import BTWifiConfig from '../../models/configModel/BTWifiConfig';
import { ConfigStateEnum, configDeviceTime } from './ConfigDeviceItem';
import configWifiModel from '../../models/configWifi';

export interface IStateDevice extends IDevice {
  state: ConfigStateEnum;
}

interface IProps {
  productConfig?: IProduct;
}

function useBleConfigManager({ productConfig }: IProps) {
  const BTWifiConfigRef = useRef(new BTWifiConfig({ productConfig }));
  const { sdkBleDevices, data } = useDeviceListStore();
  // const [bleDevices, setBleDevices] = useState<IStateDevice[]>([]);
  const [bindRecordList, setBindRecordList] = useState<IStateDevice[]>([]);
  const bindingRef = useRef(false);
  const bindQueueRef = useRef<IStateDevice[]>([]);

  const bleDevicesRef = useRef<IStateDevice[]>([]);

  const canConifgBleDevices = useMemo(() => {
    let filterPKDevices = sdkBleDevices.filter(i => i.bleWorkStatus == 1);
    if (BTWifiConfigRef.current.productConfig) {
      filterPKDevices = sdkBleDevices.filter(i => i.productKey === BTWifiConfigRef.current.productConfig.productKey);
    }
    return filterPKDevices;
  }, [sdkBleDevices])


  const list = useMemo(() => {
    let arr = bleDevicesRef.current;
    if (arr && arr.length > 0) {
      // 把ready状态的与canConifgBleDevices比较，不存在的就删掉
      arr = arr.filter((i) => {
        if (i.state == ConfigStateEnum.ready) {
          return canConifgBleDevices.findIndex((bleDevice) => isSameDevice(bleDevice, i)) > -1;
        }
        return true;
      })
    }
    bindRecordList.forEach(bindDevice => {
      const index = arr.findIndex(i => isSameDevice(bindDevice, i));
      if (index > -1) {
        arr.splice(index, 1, { ...bindDevice });
      }
    })
    bleDevicesRef.current = arr;
    return arr;
  }, [canConifgBleDevices, bindRecordList]);

  console.log('useBleConfigManager', list);

  const updateDeviceState = useCallback((device: IStateDevice) => {
    const index = bindRecordList.findIndex(bindDevice => isSameDevice(bindDevice, device));
    if (index > -1) {
      bindRecordList.splice(index, 1, device);
    } else {
      bindRecordList.push(device);
    }
    setBindRecordList([...bindRecordList]);
  }, [bindRecordList]);

  const configDeviceFunRef = useRef<(deivce: IStateDevice) => void>();

  const checkBindQueue = useCallback(() => {
    if (bindQueueRef.current && bindQueueRef.current.length > 0) {
      const device = bindQueueRef.current.splice(0, 1);
      if (configDeviceFunRef.current) {
        configDeviceFunRef.current(device[0])
      }
    }
  }, []);

  const configDevice = useCallback(async (device: IStateDevice) => {
    if (bindingRef.current) {
      // 如果绑定中，就把要绑定的设备放进绑定队列
      const index = bindQueueRef.current.findIndex(i => isSameDevice(i, device));
      if (index < 0) {
        bindQueueRef.current.push(device);
        updateDeviceState({ ...device, state: ConfigStateEnum.preLoading });
      }
      return {};
    }
    bindingRef.current = true;

    updateDeviceState({ ...device, state: ConfigStateEnum.loading });
    const configRes = await BTWifiConfigRef.current.startConfig({
      wifiName: configWifiModel.wifiName, password: configWifiModel.password, softAPSSIDPrefix: device.bleDeviceID, timeout: configDeviceTime
    });
    if (configRes.success && configRes.data && configRes.data.length > 0) {
      const cDevice = configRes.data[0];
      const deviceName = deviceDefaultName(cDevice, languageModal);
      const aepRes = await homesModel.addDevice({ device: { ...cDevice, name: deviceName } });
      console.log('aep绑定结果', aepRes);
      if (aepRes.success) {
        const aepDevice = { ...device, ...aepRes.data };
        bindingRef.current = false;
        updateDeviceState({ ...aepDevice, state: ConfigStateEnum.success });
        checkBindQueue();
        return;
      }
    }

    bindingRef.current = false;
    updateDeviceState({ ...device, state: ConfigStateEnum.fail });
    checkBindQueue();

  }, [updateDeviceState, checkBindQueue]);

  useEffect(() => {
    configDeviceFunRef.current = configDevice;
  }, [configDevice])

  return { list, sdkBleDevices, data, configDevice }
}

export default useBleConfigManager;
